package org.xxpay.manage.config.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.XXPayUtil;
import org.xxpay.core.entity.PayInterfaceType;
import org.xxpay.core.entity.PayInterfaceTypeTemplate;
import org.xxpay.manage.common.ctrl.BaseController;
import org.xxpay.manage.common.service.CommonService;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: xiaoyu
 * @date: 2019/6/20
 * @description: 支付接口类型参数模板表
 */
@RestController
@RequestMapping(Constant.MGR_CONTROLLER_ROOT_PATH + "/config/pay_interface_type/template")
public class PayInterfaceTypeTemplateController extends BaseController {

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        PayInterfaceTypeTemplate payInterfaceTypeTemplate = getObject(param, PayInterfaceTypeTemplate.class);
        int count = commonService.payInterfaceTypeTemplateService.count(payInterfaceTypeTemplate);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<PayInterfaceTypeTemplate> payInterfaceTypeTemplateList = commonService.payInterfaceTypeTemplateService.select((getPageIndex(param) -1) * getPageSize(param), getPageSize(param), payInterfaceTypeTemplate);

        for (PayInterfaceTypeTemplate interfaceTypeTemplate : payInterfaceTypeTemplateList) {

            if(interfaceTypeTemplate != null && StringUtils.isNotEmpty(interfaceTypeTemplate.getParamTemplate())){

                JSONObject paramJSON = JSON.parseObject(interfaceTypeTemplate.getParamTemplate());
                this.processParamDesensitization(interfaceTypeTemplate.getIfTypeCode(), (key) -> paramJSON.put(key, XXPayUtil.autoDesensitization(paramJSON.getString(key))));
                interfaceTypeTemplate.setParamTemplate(paramJSON.toJSONString());
            }


        }

        return ResponseEntity.ok(XxPayPageRes.buildSuccess(payInterfaceTypeTemplateList, count));
    }

    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLong(param, "id");
        PayInterfaceTypeTemplate payInterfaceTypeTemplate = commonService.payInterfaceTypeTemplateService.findById(id);

        if(payInterfaceTypeTemplate != null && StringUtils.isNotEmpty(payInterfaceTypeTemplate.getParamTemplate())){

            JSONObject paramJSON = JSON.parseObject(payInterfaceTypeTemplate.getParamTemplate());
            this.processParamDesensitization(payInterfaceTypeTemplate.getIfTypeCode(), (key) -> paramJSON.put(key, XXPayUtil.autoDesensitization(paramJSON.getString(key))));
            payInterfaceTypeTemplate.setParamTemplate(paramJSON.toJSONString());
        }

        return ResponseEntity.ok(XxPayResponse.buildSuccess(payInterfaceTypeTemplate));
    }

    @RequestMapping("/update")
    @ResponseBody
    @MethodLog( remark = "修改支付接口类型模板" )
    public ResponseEntity<?> update(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        PayInterfaceTypeTemplate payInterfaceTypeTemplate = getObject(param, PayInterfaceTypeTemplate.class);

        PayInterfaceTypeTemplate dbPayInterfaceTypeTemplate = commonService.payInterfaceTypeTemplateService.findById(payInterfaceTypeTemplate.getId());


        JSONObject updateParam = JSON.parseObject(payInterfaceTypeTemplate.getParamTemplate());
        JSONObject dbParam = JSON.parseObject(dbPayInterfaceTypeTemplate.getParamTemplate());

        this.processParamDesensitization(dbPayInterfaceTypeTemplate.getIfTypeCode(), (key) -> {
            if(StringUtils.isEmpty(updateParam.getString(key))){ //未更改
                updateParam.put(key, dbParam.getString(key));
            }
        });
        payInterfaceTypeTemplate.setParamTemplate(updateParam.toJSONString());

        int count = commonService.payInterfaceTypeTemplateService.update(payInterfaceTypeTemplate);
        if(count >= 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/add")
    @ResponseBody
    @MethodLog( remark = "新增支付接口类型模板" )
    public ResponseEntity<?> add(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        PayInterfaceTypeTemplate payInterfaceTypeTemplate = getObject(param, PayInterfaceTypeTemplate.class);
        payInterfaceTypeTemplate.setBelongInfoType(MchConstant.SYSTYPE_MGR);
        payInterfaceTypeTemplate.setBelongInfoId(0L);
        int count = commonService.payInterfaceTypeTemplateService.add(payInterfaceTypeTemplate);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    @RequestMapping("/relationDelete")
    @ResponseBody
    @MethodLog( remark = "彻底删除账号模板" )
    public ResponseEntity<?> delAccount(String ids, String superPassword, String isDeleteAlipayCash) {

        checkSecurityReq(null);  //敏感操作，用户安全认证校验

        List<Long> idsLong = JSON.parseArray(ids, Long.class);
        int delNum = commonService.payInterfaceTypeTemplateService.relationDelete(idsLong, "1".equalsIgnoreCase(isDeleteAlipayCash));
        return ResponseEntity.ok(XxPayResponse.buildSuccess(delNum));
    }

    /** 处理加密参数 **/
    private void processParamDesensitization(String ifTypeCode, PayPassageAccountController.InnerInterface callbackFunc){

        PayInterfaceType payInterfaceType = commonService.payInterfaceTypeService.findByCode(ifTypeCode);
        if(payInterfaceType != null && StringUtils.isNotEmpty(payInterfaceType.getParam())){
            JSON.parseArray(payInterfaceType.getParam()).stream().forEach(t -> {
                JSONObject tJSON = (JSONObject) t;
                if("1".equals(tJSON.getString("star"))){
                    callbackFunc.process(tJSON.getString("name"));
                }
            });
        }
    }

    // 回调接口
    interface InnerInterface{
        /** 处理 需要加密的数据 **/
        void process(String key);
    }


}
